package com.openatc.agent.service.impl;

import com.openatc.agent.service.FeatureService;
import com.openatc.agent.service.GenericMsgStrategy;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.openatc.core.common.IErrorEnumImplInner.E_110;

/**
 * @Classname FeaturePatternRequest
 * @Description 方案参数处理类
 * @Date 2022/7/20 9:02
 * @Created by panleilei
 */
@Service(value = "feature/pattern")
public class FeaturePatternRequest extends GenericMsgStrategy {

    @Autowired
    private FeatureService featureService;

    private String keyType = "response:feature/pattern:";

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 成功下载参数
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successSetProcess(MessageData requestData, RESTRet responseData) {
        String agentid = requestData.getAgentid();
        RESTRet restRet = featureService.deleteFeatureByAgentid(agentid);
        if (!restRet.isSuccess()) {
            logger.warning("MsgPostHandler process: clear feature failed!");
        }
        // 更新方案参数缓存
        updatePatternCache(agentid,requestData);
        return super.successSetProcess(requestData, responseData);
    }

    /**
     * 成功上载方案参数
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successGetProcess(MessageData requestData, RESTRet responseData) {
        // 1、上载参数成功后，更新缓存
        MessageData response = (MessageData) responseData.getData();
        String agentid = requestData.getAgentid();
        updatePatternCache(agentid,response);
        return super.successGetProcess(requestData, responseData);
    }

    /**
     * 请求方案参数失败
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet failureGetProcess(MessageData requestData, RESTRet responseData) {
        // 从缓存中获取参数
        InnerError innerError1 = (InnerError) responseData.getData();
        if (innerError1.getErrorCode().equals(E_110.getErrorCode())) {
           return redisTemplateUtil.getCacheData(requestData);
        }
        return super.failureGetProcess(requestData,responseData);
    }


    /**
     * 更新方案缓存数据
     * @param agentid
     * @param data
     */
    private void updatePatternCache(String agentid, MessageData data) {
        String key = keyType + agentid;
        data.setOperation("get-response");
        data.setInfotype("feature/pattern");
        data.setCreatetime(DateUtil.date2str(new Date()));
        redisTemplateUtil.setValue(key,gson.toJson(data));
    }


}
